<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image
            src="/svgs/titleIcon.svg"
            style="width: 17px; margin-top: 2px"
            fit
          />
        </el-breadcrumb-item>
        <el-breadcrumb-item>数据中心</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'dataset' }"
          >数据集</el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><span style="color: #333;"
            >数据详情</span
          ></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="title">数据详情</div>
      <div class="contentBox">
        <div class="dataBox">
          <div class="row">
            <div class="col">
              数据集名称：<i>{{ datasetObj.title }}</i>
            </div>
            <div class="col">
              创建时间：<i>{{ datasetObj.create_at }}</i>
            </div>
            <div class="col">
              最新版本号：<i>{{ datasetObj.version_latest }}</i>
            </div>
            <div class="col"></div>
          </div>
          <div class="row">
            <div class="col">
              数据集说明：<i>{{ datasetObj.description }}</i>
            </div>
            <div class="col">
              数据类型：<i>{{ datasetObj.dataset_type_zh }}</i>
            </div>
            <div class="col">
              创建人：<i>{{ datasetObj.creator }}</i>
            </div>
            <div class="col"></div>
          </div>
        </div>
      </div>
      <el-tabs
        v-model="activeName"
        @tab-click="handleSelect"
        :before-leave="confirmLeave"
      >
        <div v-if="!dataVersionListShow " style="height: 22px;width: 100%;background-color: #fff"></div>
        <el-tab-pane label="概览" name="first">
          <div style="min-height: 50px; position: relative">
            <div style="display: flex; justify-content: flex-end;background-color: #fff">
              <el-button
                v-if="!isEditor && editorShow"
                type="primary"
                @click="editor"
                style="margin-bottom: 10px; font-size: 14px"
              >编辑</el-button
              >
              <transition name="el-fade-in-linear">
                <div v-if="isEditor" style="margin-bottom: 10px">
                  <el-button
                    type="primary"
                    :disabled="deleteBtnDisabled"
                    size="small"
                    @click="handleDialogDelete"
                  >删除</el-button
                  >
                  <el-button
                    type="primary"
                    @click="datasetImport"
                    size="small"
                  >导入</el-button
                  >
                  <el-button type="primary" size="small" @click="saveToDialog"
                  >保存</el-button
                  >
                </div>
              </transition>
            </div>
            <el-table
              height="300"
              :data="responseDataList.files"
              style="width: 100%"
              :header-cell-style="{
                  background: '#f9f9f9',
                  color: '#333333',
                  fontSize: '14px',
                  fontWeight: '500'
                }"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" v-if="isEditor" />
              <el-table-column label="文件名称" prop="file_info.row_name">
                <template #default="scope">
                  <el-button
                    link
                    @click="openDialog(scope.row)"
                    style="
                        color: #3d5ce4;
                        font-size: 14px;
                      "
                  >{{ scope.row.file_info.row_name }}</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="文件大小"
                prop="file_info.file_size"
              ></el-table-column>
              <el-table-column
                label="格式"
                prop="file_info.format"
              ></el-table-column>
              <el-table-column
                label="上传时间"
                prop="file_info.create_at"
              >
                <template #default="scope">
                  {{ scope.row.file_info.create_at ? scope.row.file_info.create_at : '-' }}
                </template>
              </el-table-column>
              <template #empty>
                <div class="noData">暂无数据</div>
              </template>
            </el-table>
          </div>

          <div
            class="row"
            style="justify-content: flex-end;background-color: #fff;margin-bottom: 20px"
            v-if="responseDataList.files.length > 0"
          >
            <el-pagination
              background
              layout="prev, pager, next, sizes, jumper"
              :total="tableData.count"
              style="margin-top: 20px"
              :page-sizes="[10, 20, 50]"
              @size-change="sizeChange"
              :current-page="pageDataValue.page"
              @current-change="changePage"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="版本管理" name="second">
          <div style="background-color: #fff">
            <div
              v-if="dataVersionListShow"
              style="
                  color: #1d1d1d;
                  padding: 10px 0 10px 10px;
                  cursor: pointer;
                "
              @click="dataVersionListShow = false"
            >
              {{ gobackText }}
            </div>

            <el-table
              v-if="dataVersionListShow"
              height="300"
              :data="dataVersionList.files"
              style="width: 100%; font-size: 14px"
              :header-cell-style="{ background: '#f9f9f9', color: '#333', fontweight: '500', fontSize: '14px' }"
            >
              <el-table-column
                align="center"
                prop="file_info.row_name"
                label="文件名称"
              />
              <el-table-column
                align="center"
                prop="file_info.file_size"
                label="文件大小"
              />
              <el-table-column
                align="center"
                prop="file_info.format"
                label="格式"
              />
              <el-table-column
                align="center"
                prop="file_info.create_at"
                label="上传时间"
              />
            </el-table>

            <el-table
              v-else
              height="300"
              :data="responseData.results"
              style="width: 100%; font-size: 14px"
              :header-cell-style="{ background: '#f9f9f9', color: '#333333', fontWeight: '500' }"
            >
              <el-table-column
                align="center"
                prop="title"
                label="版本名称"
                width="180"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="getDataVersion(scope.row.title)"
                  >{{ scope.row.title }}</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="create_time"
                label="发布时间"
              />
              <el-table-column
                align="center"
                prop="simple_count"
                label="样本数量"
              />
              <el-table-column align="center" prop="labels" label="操作">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="deleteData(scope.row.id)"
                  >删除</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="shareDataSet(scope.row.id)"
                  >分享</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="
                        router.push({
                          name: 'dataAnnotations-create',
                          params: { project_id: projectId },
                        })
                      "
                  >创建标注任务</el-button
                  >
                </template>
              </el-table-column>
              <template #empty>
                <div class="noData">暂无数据</div>
              </template>
            </el-table>
          </div>
          <div
            class="row"
            style="justify-content: flex-end;background-color: #fff;margin-bottom: 20px"
            v-if="responseData.results.length > 0 && !dataVersionListShow"
          >
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="responseData.count"
              style="margin-top: 20px"
              :page-sizes="[10, 20, 50]"
              @size-change="sizeVersionChange"
              :current-page="pageVersionValue.page"
              @current-change="changeVersionPage"
            />
          </div>

          <div
            class="row"
            style="justify-content: flex-end;background-color: #fff;margin-bottom: 20px"
            v-if="dataVersionList.files.length > 0 && dataVersionListShow"
          >
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataVersionList.count"
              style="margin-top: 20px"
              :page-sizes="[10, 20, 50]"
              @size-change="sizeDataVersionChange"
              :current-page="pageDataVersionValue.page"
              @current-change="changeDataVersionPage"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="标注任务" name="third" style="background-color: #fff">
          <div>
            <el-table
              :data="taskData"
              style="width: 100%; font-size: 14px"
              :header-cell-style="{
                  background: '#f9f9f9',
                  color: '#333',
                  textAlign: 'left',
                  fontWeight: '500',
                  fontSize: '14px'
                }"
            >
              <el-table-column
                align="left"
                prop="title"
                label="名称"
                width="120"
              />
              <el-table-column
                align="left"
                prop="label_type_zh"
                label="标注类型"
                width="120"
              />
              <el-table-column
                align="left"
                label="标注进度（已标注个数/总数）"
                width="140"
              >
                <template #default="scope">
                  {{
                    scope.row.data_statistic &&
                    scope.row.data_statistic.labeled_number ==
                    scope.row.data_statistic.total_number
                      ? '0.00'
                      : scope.row.data_statistic &&
                      (
                        (scope.row.data_statistic.labeled_number /
                          scope.row.data_statistic.total_number) *
                        100
                      ).toFixed(2)
                  }}%
                </template>
              </el-table-column>
              <el-table-column align="left" label="样本数量">
                <template #default="scope">
                  {{
                    scope.row.data_statistic
                      ? scope.row.data_statistic.total_number
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column
                align="left"
                prop="create_at"
                label="创建时间"
              />
              <el-table-column
                align="left"
                prop="dataset_version"
                label="关联数据集版本"
              />
              <el-table-column align="left" prop="description" label="描述" />
              <el-table-column align="left" prop="labels" label="操作">
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="enterTask(scope.row)"
                  >进入任务</el-button
                  >
                </template>
              </el-table-column>
              <template #empty>
                <div class="noData">暂无数据</div>
              </template>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog
        v-model="dialogTips"
        title="数据集分享链接"
        width="400"
        class="copyTip"
      >
        <el-input
          v-model="shareUrl"
          disabled
          input-style="width:280px;-webkit-text-fill-color:#333;"
          style="margin-right: 30px"
        />
        <el-button
          type="primary"
          @click="copyButton"
          data-clipboard-target="#password"
        >
          <el-icon>
            <img style="width: 16px" :src="copyIcon" />
          </el-icon>
        </el-button>
      </el-dialog>
      <!--概览文件名称弹框-->
      <el-dialog
        v-model="dataPreview"
        title="数据预览"
        :show-close="false"
        @close="closeDialog"
        :close-on-click-modal="false"
      >
        <div v-if="!textContent" style="display: flex; justify-content: center">
          <img
            :src="dataPreviewList.file_info.url"
            style="
              width: 50%;
              min-width: 200px;
              min-height: 200px;
              object-fit: contain;
            "
          />
        </div>

        <pre
          v-else
          style="
            height: 300px;
            overflow: auto;
            white-space: pre-wrap;
            overflow-x: auto;
          "
          v-html="textContent"
        ></pre>
        <div style="display: flex; justify-content: center; margin-top: 20px">
          <el-button type="primary" @click="dataPreview = false"
            >关闭</el-button
          >
        </div>
      </el-dialog>

      <!-- 修改标注信息 -->
      <el-dialog
        v-model="dialogSetLabelData"
        title="修改标注信息"
        width="400"
        :show-close="false"
        @close="closeDialog"
        :close-on-click-modal="false"
      >
        <el-form
          ref="ruleFormRef"
          :model="formLabelAlign"
          label-position="right"
          label-width="100px"
          style="max-width: 460px"
        >
          <el-form-item label="任务名称：" prop="title">
            <el-input
              v-model.trim="formLabelAlign.title"
              input-style="width:180px"
            />
          </el-form-item>
          <el-form-item label="任务描述：" prop="description">
            <el-input
              v-model="formLabelAlign.description"
              input-style="width:180px"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogSetLabelData = false">取消</el-button>
            <el-button type="primary" @click="setData()"> 确认修改 </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 删除标注任务 -->
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 350px">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px">
              <el-icon
                style="
                  color: #ff5656;
                  display: inline-block;
                  vertical-align: middle;
                  margin-top: -3px;
                  font-size: 20px;
                "
              >
                <WarningFilled />
              </el-icon>
              删除提示
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            <div>确定删除本条数据吗？</div>
            <div>删除后不可恢复，请谨慎操作！</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary">
            <el-button type="primary" plain v-close-popup>取消</el-button>
            <el-button type="primary" @click="deleteLabelData"
              >确认删除</el-button
            >
          </q-card-actions>
        </q-card>
      </q-dialog>
      <!--编辑-删除-->

      <!--删除概览列表数据-->
      <el-dialog
        v-model="deleteRoleDialog"
        :show-close="false"
        width="500px"
        :close-on-click-modal="false"
      >
        <template #header="{}">
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-top: 10px;
            "
          >
            <div style="display: flex">
              <el-icon style="font-size: 20px; color: #ffa940"
                ><WarningFilled
              /></el-icon>
              <span style="margin-left: 10px; color: #ffa940; font-weight: bold"
                >删除提醒</span
              >
            </div>
          </div>
        </template>
        <div style="margin: 0 0 50px 50px; padding: 0">
          确定删除选中的数据嘛?删除后不可恢复,请谨慎操作！
        </div>
        <div
          style="
            display: flex;
            justify-content: flex-end;
            margin-right: 10px;
            margin-bottom: 10px;
          "
        >
          <el-button @click="keepDelete">确认删除</el-button>
          <el-button type="primary" @click="deleteRoleDialog = false"
            >放弃删除</el-button
          >
        </div>
      </el-dialog>

      <!--编辑导入-->
      <el-dialog
        title="导入数据"
        v-model="datasetImportDialog"
        :show-close="true"
        width="500px"
        :close-on-click-modal="false"
        class="datasetImportDialog"
      >
        <el-form
          :model="datasetImportForm"
          :rules="datasetImportRules"
          ref="datasetImportRef"
          :label-position="'right'"
          label-width="110px"
          status-icon
          @submit.prevent
        >
          <el-form-item label="数据集名称">
            <p style="margin: 0">{{ datasetObj.title }}</p>
          </el-form-item>
          <el-form-item label="数据类型">
            <p style="margin: 0">{{ datasetObj.dataset_type_zh }}</p>
          </el-form-item>
          <el-form-item
            label="数据上传"
            class="labelContent"
            prop="file_ids"
            ref="imageOfFrom"
          >
            <el-tabs style="" class="demo-tabs">
              <div class="row labelTypeBox">
                <el-upload
                  ref="uploadRef"
                  class="upload-demo uploadBox"
                  :show-file-list="false"
                  drag
                  :http-request="uploadFile"
                  :file-list="uploadFileList"
                  multiple
                  :on-change="handleFileChanged"
                  :on-remove="removeListData"
                  :before-upload="checkFileType"
                >
                  <div
                    class="el-upload__text uploadBoxBtn"
                    style="line-height: 24px"
                  >
                    <el-image :src="imgUrl" fit />
                    <div style="color: #333; font-size: 14px">
                      点击选择文件或将文件拖拽到这里上传
                    </div>
                    <div style="color: #999; font-size: 14px">
                      支持上传文件格式：
                    </div>
                    <div style="color: #999; font-size: 14px">
                      {{ textFromRes[0].format }}
                    </div>
                  </div>
                </el-upload>
                <div
                  style="width: 280px; max-width: 500px"
                  :class="{ listOverflowScroll: uploadFileList.length > 4 }"
                >
                  <ul class="el-upload-list el-upload-list--text">
                    <li
                      class="el-upload-list__item is-success"
                      v-for="(item, index) in uploadFileList"
                      :key="index"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <a
                        class="el-upload-list item-name"
                        style="
                          width: 80%;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          max-width: 300px;
                        "
                      >
                        <i class="el-icon-document"> </i>
                        {{ item.row_name }}
                      </a>
                      <el-icon
                        style="margin-top: 5px"
                        @click="handleRemove(index)"
                        ><Close
                      /></el-icon>
                    </li>
                  </ul>
                </div>
              </div>
            </el-tabs>
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="display: flex; justify-content: flex-end; padding: 0">
            <el-button @click="handleCloseDialog(datasetImportRef)"
              >取消</el-button
            >
            <el-button type="primary" @click="uploadImport(datasetImportRef)">
              上传
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!--保存弹框-->
      <el-dialog
        v-model="saveDialog"
        :show-close="false"
        width="500px"
        :close-on-click-modal="false"
      >
        <template #header="{}">
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-top: 10px;
            "
          >
            <div style="display: flex">
              <!--              <el-icon style="font-size: 20px; color: rgb(250,173,21)"><WarningFilled /></el-icon>-->
              <span style="margin-left: 10px; color: #1d1d1d; font-weight: bold"
                >保存提醒</span
              >
            </div>
          </div>
        </template>
        <el-form
          :label-position="labelPosition"
          ref="saveDialog"
          :model="saveDialogForm"
          :rules="saveDialogRules"
          style="margin-left: 25px"
        >
          <el-form-item label="当前版本号" style="margin-left: 25px">
            <p style="margin: 0">{{ datasetObj.version_latest }}</p>
          </el-form-item>
          <el-form-item label="请输入版本号" prop="beforeVersion">
            <el-input
              placeholder="请输入更改后的版本号"
              v-model="saveDialogForm.beforeVersion"
            ></el-input>
          </el-form-item>
          <div
            style="
              display: flex;
              justify-content: flex-end;
              margin-right: 10px;
              margin-bottom: 10px;
            "
          >
            <el-button
              type="primary"
              @click="
                noConfirmSave(saveDialog, onBeforeRouteLeaveData, nextData)
              "
              >放弃保存</el-button
            >
            <el-button
              @click="confirmSave(saveDialog, onBeforeRouteLeaveData, nextData)"
              >确认保存</el-button
            >
          </div>
        </el-form>
      </el-dialog>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import copyIcon from 'assets/dataSet/copyIcon.png';
import {
  reactive,
  ref,
  shallowRef,
  watch,
  computed,
  toRaw,
  nextTick,
} from 'vue';
import { Search, Edit } from '@element-plus/icons-vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import {
  getDatasetDetail,
  shartDataSet,
  versionManage,
  deleteVeersionData,
  deletedataLabel,
  setLabelData,
  getDatasetDetailVersions,
  handleEditor,
  deleteDatasetListData,
  getDatasetType,
  importData,
  resoveVersion,
  cancleResoveVersion,
  getDataFileFromVersion,
  getDatasetsAnnotation,
  getTextContent,
  getTextContentInfo,
} from 'src/api/dataset';
import imgUrl from 'assets/dataSet/grayUpload.png';
import VueResource from 'vue-resource';
import { dataSetStore } from 'src/stores/dataSet';
import useClipboard from 'vue-clipboard3';
import {
  ElMessage,
  ElMessageBox,
  ElNotification,
  FormInstance,
  FormRules,
} from 'element-plus';
import boxLoading from 'src/components/boxLoading.vue';
import { Interp } from '@antv/x6';
import object = Interp.object;
import { uploadFileApi } from 'src/api/common';
const router = useRouter();
const imageOfFrom = ref();
const labelPosition = ref('right');
const projectId = router.currentRoute.value.params.project_id;
const dataId = dataSetStore().dataset_id;
let dataVersion = dataSetStore().versionData;
const dialogTips = ref(false);
const activeName = ref('first');
let chooseNumber = ref('1');
const loading = ref(true);
const tableData = shallowRef({
  count: 0,
  results: [],
});
const pageDataValue = ref({
  page: 1,
  page_size: 10,
});
const pageVersionValue = ref({
  page: 1,
  page_size: 10,
});
const pageDataVersionValue = ref({
  page: 1,
  page_size: 10,
});
let datasetObj = shallowRef({
  title: '',
  label_title: '',
  description: '',
  create_at: '',
  creator: '',
  data_title: '',
  progress: '',
  status: '',
});
const dialogDeleteData = ref(false);
const deleteDataId = ref();
const dialogSetLabelData = ref(false);
const isEditor = ref(false);
const deleteRoleDialog = ref(false);
const deleteBtnDisabled = ref(true); //编辑删除按钮是否可用
const deleteDataIdList = ref([]);
const datasetImportDialog = ref(false);
const paramObj = shallowRef();
const boxLoadState = ref(false);
const uploadFileList: any = ref([]);
const textFromRes = ref([]);
const datasetImportRef = ref();
const saveDialog = ref(false);
const editorShow = ref(true);
const onBeforeRouteLeaveData = ref(false);
const gobackText = ref('< 返回');
const dataVersionList = ref({
  count: 0,
  files: [],
}); //版本下的数据集文件
const dataVersionTitle = ref('');
let textContent = ref(''); //上传文本数据
let imageUrl = ref('');

const dataVersionListShow = ref(false); //文件表格和版本管理切换
const nextData = ref();
const uploadDataReminder = ref(false);
const formLabelAlign = reactive({
  title: '',
  description: '',
});
const dataPreview = ref(false);
const dataPreviewList = ref({});
const saveDialogForm = reactive({
  beforeVersion: '',
});
const saveDialogRules = reactive<FormRules>({
  beforeVersion: [
    { required: true, message: '请输入更改后的版本号', trigger: 'blur' },
  ],
});
const pageData = ref({
  page: 1,
});
let responseDataList = ref({
  count: 0,
  files: <any>[],
});
let responseData = ref({
  count: 0,
  next: null,
  previous: null,
  results: <any>[],
});
let taskData = ref([]);
function getDataVersion(title: string) {
  dataVersionTitle.value = title;
  let obj = { version: title };
  obj = Object.assign(obj, pageDataVersionValue.value);
  getDataFileFromVersion(projectId, dataId, obj).then((res: any) => {
    dataVersionList.value = res.data;
    dataVersionListShow.value = true;
  });
}

//返回上个页面
function goBack() {
  if (uploadDataReminder.value) {
    ElMessage({
      message: '请先上传文件',
      type: 'error',
    });
  } else {
    if (isEditor.value) {
      saveDialog.value = true;
      onBeforeRouteLeaveData.value = true;
    } else {
      router.go(-1);
    }
  }
}
//进入任务
function enterTask(row: any) {
  dataSetStore().setUseData(row.id, row.annotation_config, row.label_type,row.title);
  dataSetStore().taskId(row.id);
  dataSetStore().setLabelsArr(row.labels);
  router.push({
    name: 'dataAnnotations-dimension',
    params: { project_id: projectId },
  });
}

const saveVersion = ref('');

//编辑
function editor() {
  loading.value = true;
  partLoading.value = true;
  handleEditor(projectId, dataId, {
    version: datasetObj.value.version_latest,
  }).then((res: any) => {
    saveVersion.value = res.data.version;
    getDataFileFromVersion(projectId, dataId, {
      version: res.data.version.version,
    })
      .then((res: any) => {
        responseDataList.value = res.data;
      })
      .finally(() => {
        loading.value = false;
        partLoading.value = false;
      });
    isEditor.value = true;
  });
}

//
function openDialog(row: any) {
  let dataList = JSON.parse(JSON.stringify(row));
  dataPreview.value = true;
  dataPreviewList.value = row;
  if (
    dataList.file_info.format === 'txt' ||
    dataList.file_info.format === 'tsv' ||
    dataList.file_info.format === 'csv' ||
    dataList.file_info.format === 'pdb' ||
    dataList.file_info.format === 'fasta'
  ) {
    getTextContent(row.file_info.url).then((res: any) => {
      textContent.value = res.data;
    });
  }
}

//列表多选
const handleSelectionChange = (val: any) => {
  let dataList = JSON.parse(JSON.stringify(val));
  if (dataList.length > 0) {
    deleteDataIdList.value = dataList.map((item: any) => item.id);
    deleteBtnDisabled.value = false;
  } else {
    deleteBtnDisabled.value = true;
  }
};
//删除弹框
function handleDialogDelete() {
  deleteRoleDialog.value = true;
}
//删除事件
function keepDelete() {
  deleteDatasetListData(projectId, dataId, {
    data_ids: deleteDataIdList.value,
    version: saveVersion.value.version,
  }).then((res: any) => {
    ElMessage.success('删除成功！');
    datasetDetailVersions();
    deleteRoleDialog.value = false;
  });
}
//导入事件
function datasetImport() {
  getDatasetType().then((res: any) => {
    textFromRes.value = res.data.filter(
      (item: any) => item.type === datasetObj.value.dataset_type
    );
    datasetImportDialog.value = true;
  });
}
function saveToDialog() {
  if (uploadDataReminder.value) {
    ElMessage({
      message: '请先上传文件',
      type: 'error',
    });
  } else {
    saveDialog.value = true;
  }
}
const datasetImportForm = reactive({
  file_ids: <any>[],
});
const datasetImportRules = reactive<FormRules>({
  file_ids: [
    {
      required: true,
      message: '数据上传不能为空',
      trigger: ['blur', 'change'],
    },
  ],
});

onBeforeRouteLeave((to, from, next) => {
  if (uploadDataReminder.value) {
    ElMessage({
      message: '请先上传文件',
      type: 'error',
    });
  } else {
    if (isEditor.value) {
      saveDialog.value = true;
      nextData.value = next;
      onBeforeRouteLeaveData.value = true;
    } else {
      next();
    }
  }
});

//确认保存
const confirmSave = async (
  formEl: FormInstance | undefined,
  onBeforeRouteLeaveData,
  next: any
) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleSaveEvent(onBeforeRouteLeaveData, next);
    }
  });
};

function handleSaveEvent(onBeforeRouteLeaveData: boolean, next: any) {
  resoveVersion(projectId, dataId, {
    is_save: true,
    new_version: saveDialogForm.beforeVersion,
    pre_version: saveVersion.value.version,
  }).then((res: any) => {
    saveDialog.value = false;
    isEditor.value = false; //防止出现点击放弃保存路由拦截再次弹框
    if (!onBeforeRouteLeaveData) {
      router.go(-1);
    } else {
      router.go(-1);
    }
  });
}
//取消保存
const noConfirmSave = (
  formEl: FormInstance | undefined,
  onBeforeRouteLeaveData: boolean,
  next: any
) => {
  if (!formEl) return;
  cancleResoveVersion(projectId, dataId, {
    is_save: false,
    pre_version: saveVersion.value.version,
  }).then((res: any) => {
    saveDialog.value = false;
    isEditor.value = false; //防止出现点击放弃保存路由拦截再次弹框
    if (!onBeforeRouteLeaveData) {
      router.go(-1);
    } else {
      router.go(-1);
    }
  });
};

const uploadImport = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      importData(projectId, dataId, {
        version: saveVersion.value.version,
        file_ids: datasetImportForm.file_ids,
      }).then((res: any) => {
        ElNotification({
          title: 'Success',
          message: '导入成功',
          type: 'success',
        });
        datasetDetailVersions();
        imageOfFrom.value.clearValidate();
        uploadRef.value?.clearFiles();
        uploadFileList.value = [];
        datasetImportForm.file_ids = [];
        datasetImportDialog.value = false;
      });
    }
  });
};
const uploadRef = ref();
const handleCloseDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  uploadRef.value?.clearFiles();
  datasetImportForm.file_ids = [];
  datasetImportDialog.value = false;
};

function checkFileType(file: any, fileList: any) {
  const fileName = file.name;
  const fileTypeName = fileName.substring(fileName.lastIndexOf('.') + 1);
  const isFileType = textFromRes.value[0]['format'].includes(fileTypeName);
  if (isFileType == false) {
    ElMessage.error(
      `上传类型错误，请选择${textFromRes.value[0]['format']}格式文件`
    );
    fileList.pop();
  }
  let isLt2k = file.size / 1024 / 1024 / 1024 < 2 ? '1' : '0';
  if (isLt2k == '0') {
    ElMessage.error(`上传文件过大，请选择小于2G的文件`);
    fileList.pop();
  }
}

function uploadFile(obj: any) {
  imageOfFrom.value.clearValidate();
  paramObj.value = new FormData();
  paramObj.value.append('file', obj.file);
  paramObj.value.append('date', obj.file.name);
  uploadFileApi(paramObj.value).then((res) => {
    uploadFileList.value.push(res.data);
    datasetImportForm.file_ids.push(res.data.id);
  });
}
function handleRemove(index: number) {
  boxLoadState.value = true;
  uploadFileList.value.splice(index, 1);
  datasetImportForm.file_ids.splice(index, 1);
  boxLoadState.value = false;
}
const handleFileChanged = (file: any, fileList: any) => {
  // 检查是否有重复文件
  if (
    fileList.findIndex((f: any) => f.name === file.name) !=
    fileList.findLastIndex((f: any) => f.name === file.name)
  ) {
    ElMessage.error(file.name + '该文件已存在');
    fileList.pop();
    uploadFileList.value.pop();
    datasetImportForm.file_ids.pop();
  }
};
// 删除上传文件列表的某个值
function removeListData(file: any, fileList: any) {
  let filterArrIndex = uploadFileList.value.findIndex((item: any) => {
    return item.file.indexOf(file.name) > -1;
  });
  uploadFileList.value.splice(filterArrIndex, 1);
  datasetImportForm.file_ids.splice(filterArrIndex, 1);
}

//监听vuex数据变化 修改切换初始值
const getChooseNumber = computed(() => {
  //返回的是ref对象
  return dataSetStore().chooseNumber;
});
watch(
  getChooseNumber,
  (newVal, oldVal) => {
    if (newVal === '1') {
      activeName.value = 'first';
      datasetDetailVersions();
    } else if (newVal === '2') {
      activeName.value = 'second';
      editorShow.value = false;
      versionData();
    }
  },
  { immediate: true, deep: true }
);

function confirmLeave(active: string) {
  if (active === 'second' || active === 'third') {
    if (uploadDataReminder.value) {
      ElMessage({
        message: '请先上传文件',
        type: 'error',
      });
      return false;
    } else {
      if (isEditor.value) {
        saveDialog.value = true;
        onBeforeRouteLeaveData.value = true;
      } else {
        return true;
      }
    }
  }
}
const handleSelect = (key: string, keyPath: string[]) => {
  const activeTab = JSON.parse(JSON.stringify(activeName.value));
  if (activeTab == 'first') {
    datasetDetailVersions();
    editorShow.value = true;
  }
  if (activeTab == 'second') {
    if (uploadDataReminder.value) {
      ElMessage({
        message: '请先上传文件',
        type: 'error',
      });
    } else {
      if (isEditor.value) {
        saveDialog.value = true;
      } else {
        versionData();
      }
      editorShow.value = false;
    }
  }
  if (activeTab == 'third') {
    if (uploadDataReminder.value) {
      ElMessage({
        message: '请先上传文件',
        type: 'error',
      });
    } else {
      if (isEditor.value) {
        saveDialog.value = true;
      } else {
        labelData();
      }
      editorShow.value = false;
    }
  }
};
// const handleSelect = (key: string, keyPath: string[]) => {
//   responseDataList.value.files = []
//   responseData.value.results = [];
//   chooseNumber.value = key;
//   // activeIndex.value = '1';
//   if (key == '1') { datasetDetailVersions(); editorShow.value = true};
//   if (key == '2') {
//     if( isEditor.value ){
//       saveDialog.value = true;
//     }else {
//       versionData();
//     }
//     // editorShow.value = false;
//   };
//   if (key == '3') {
//     if( isEditor.value ){
//       saveDialog.value = true;
//     }
//     labelData();
//     editorShow.value = false;
//   };
// }
const partLoading = ref(false);
const userStatus = JSON.parse(localStorage.getItem('user') || '{}').status; //判断用户是否是项目创建人或项目管理员

getData();
function getData() {
  loading.value = true;
  getDatasetDetail(projectId, dataId)
    .then((res: any) => {
      datasetObj.value = res.data;
    })
    .finally(() => {
      loading.value = false;
    });
}

//获取概览数据表
function datasetDetailVersions() {
  let versionData = saveVersion.value.version
    ? saveVersion.value.version
    : dataVersion;
  loading.value = true;
  getDatasetDetailVersions(projectId, dataId, {
    version: versionData,
    page: pageDataValue.value.page,
    page_size: pageDataValue.value.page_size,
  })
    .then((res: any) => {
      responseDataList.value = res.data;
      tableData.value = res.data;
      if (res.data.files.length === 0) {
        uploadDataReminder.value = true; //请先指向导入数据操作
      } else {
        uploadDataReminder.value = false;
      }
    })
    .finally(() => {
      loading.value = false;
      partLoading.value = false;
    });
}
function sizeChange(pageSize: any) {
  pageDataValue.value.page_size = pageSize;
  pageDataValue.value.page = 1;
  datasetDetailVersions();
}
function sizeVersionChange(pageSize: any) {
  pageVersionValue.value.page_size = pageSize;
  pageVersionValue.value.page = 1;
  versionData();
}
function sizeDataVersionChange(pageSize: any) {
  pageDataVersionValue.value.page_size = pageSize;
  pageDataVersionValue.value.page = 1;
  getDataVersion(dataVersionTitle.value);
}
function changePage(currentPage: any) {
  pageDataValue.value.page = currentPage;
  datasetDetailVersions();
}
function changeVersionPage(currentPage: any) {
  pageVersionValue.value.page = currentPage;
  versionData();
}
function changeDataVersionPage(currentPage: any) {
  pageDataVersionValue.value.page = currentPage;
  getDataVersion(dataVersionTitle.value);
}
// 获取版本管理列表
function versionData() {
  loading.value = true;
  versionManage(projectId, dataId, pageVersionValue.value)
    .then((res: any) => {
      console.log('yes',res);
      responseData.value = res.data;
      dataVersion = res.data.results[0].title;
      dataSetStore().versionset(res.data.results[0].title);
      getData(); //重新获取数据详情的数据
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
      partLoading.value = false;
    });
}
// 版本管理-删除
function deleteData(version_id: number) {
  if (responseData.value.results.length === 1) {
    ElMessageBox.confirm('删除仅存的版本后，数据集也会删除', '提示', {
      confirmButtonText: '确定',
      showCancelButton: false,
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      loading.value = true;
      deleteVeersionData(projectId, dataId, version_id)
        .then(() => {
          ElMessage.success('删除成功！');
        })
        .finally(() => {
          router.push({
            name: 'dataset',
            params: { project_id: projectId },
          });
        });
    });
  } else {
    ElMessageBox.confirm('确定删除该条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showClose: true,
      type: 'warning',
    }).then(() => {
      loading.value = true;
      deleteVeersionData(projectId, dataId, version_id)
        .then(() => {
          ElMessage.success('删除成功！');
        })
        .finally(() => {
          versionData();
          loading.value = false;
        });
    });
  }
}
// 标注任务
function labelData() {
  loading.value = true;
  getDatasetsAnnotation(projectId, { dataset_id: dataId })
    .then((res: any) => {
      console.log('res.data', res.data);
      taskData.value = res.data.results;
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
      partLoading.value = false;
    });
}

const shareUrl = ref('');
function shareDataSet(version_id: number) {
  shartDataSet(projectId, dataId, version_id)
    .then((res: any) => {
      shareUrl.value = res.data.url;
      dialogTips.value = true;
    })
    .finally(() => {
      console.log('success');
    })
    .catch((error) => {
      console.log(error);
    });
}
// 复制分享链接
const { toClipboard } = useClipboard();
const copyButton = async () => {
  try {
    await toClipboard(shareUrl.value);
    ElMessage({
      message: '数据集链接已复制',
      type: 'success',
    });
  } catch (e) {
    console.error(e);
  }
};

const stateText = (str: string) => {
  switch (str) {
    case 'importing':
      return '导入中';
    case 'completed':
      return '导入成功';
    case 'failed':
      return '导入失败';
  }
};
function toLabelPage(
  id: number,
  labels: [],
  config: string,
  type: string,
  dataSetId: number
) {
  dataSetStore().setUseData(id, config, type);
  dataSetStore().dataset(dataSetId);
  dataSetStore().setLabelsArr(labels);
  router.push({
    name: 'dataAnnotations-dimension',
    params: { project_id: projectId },
  });
}
function deleteLabelData() {
  deletedataLabel(projectId, deleteDataId.value)
    .then((res: any) => {
      dialogDeleteData.value = false;
      ElNotification({
        title: 'Success',
        message: '删除成功',
        type: 'success',
      });
      labelData();
    })
    .catch((error) => {
      console.log(error);
    });
}
function closeDialog() {
  formLabelAlign.title = '';
  formLabelAlign.description = '';
}
const label_id = ref();
function openSetPopup(id: number) {
  dialogSetLabelData.value = true;
  label_id.value = id;
}
function setData() {
  setLabelData(projectId, label_id.value, formLabelAlign)
    .then((res: any) => {
      ElNotification({
        title: 'Success',
        message: '修改成功',
        type: 'success',
      });
      dialogSetLabelData.value = false;
      labelData();
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      console.log('success');
    });
}
// function changePage(currentPage: any) {
//   pageData.value.page = currentPage
//   let chooseKey = chooseNumber.value
//   if (chooseKey == '1') datasetDetailVersions()
//   if (chooseKey == '2') {
//     alert(11);
//     if( isEditor.value ){
//       saveDialog.value = true;
//     }else {
//       versionData()
//     };
//   }
//   if (chooseKey == '3') labelData()
// }
</script>

<style lang="scss" scoped>
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: #f6f8fa;
    height: 46px;
    ::v-deep .el-breadcrumb {
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-size: 16px;
      font-weight: 500;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .demo-tabs {
        margin-top: 40px;
      }
    }
  }
}
//选项卡不要下边距
::v-deep .el-tabs__header{
 margin: 0!important;
}

::v-deep .is-message-box{
  z-index: 9999!important;
}
//修改tab选项卡下划线
::v-deep .el-tabs__nav-wrap::after{
  height: 1px!important;
  ackground-color: var(--nav-bg-color)!important;
}
//el-tabs__nav
::v-deep .el-tabs__nav{
  transform: translateX(10px)!important;
}
//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 14px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}
//面包屑字体颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}
::v-deep .el-tabs__active-bar {
  display: none;
}
::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}

::v-deep .el-tabs__item{
  padding: 0 20px!important;
  color: #333;
  font-weight: 500;
  font-size: 14px;
}
::v-deep .is-active {
  color: #3d5ce4;
  background: #3d5ce41a;
  font-weight: 500;
  font-size: 14px;
}
::v-deep .el-upload-dragger {
  background-color: #fafafa !important;
}
::v-deep .datasetImportDialog .el-dialog__body {
  padding: 10px 0 0 0 !important;
}
::v-deep .datasetImportDialog .el-dialog__footer {
  padding-top: 0 !important;
}
:deep(.el-input__inner::placeholder) {
  color: #cccccc;
  font-size: 14px;
  font-weight: 400;
}
::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}
.listOverflowScroll {
  height: 200px;
  overflow: scroll;
}

::v-deep disabled,
::v-deep .disabled *,
::v-deep [disabled],
::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}
::v-deep .el-menu--horizontal {
  margin-bottom: 0 !important;
}
::v-deep .el-dialog__header {
  margin: 0;
  border-bottom: 1px solid rgb(234, 234, 234);
}
.dataBox {
  .row {
    margin-bottom: 12px;
    font-size: 14px;
    .col{
      color: #666;
    }
    i {
      font-style: initial;
      color: #333;
    }
  }
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
  margin: 0 10px 0 -10px;
}

.successDot {
  background: #1fb62f;
}

.pendingDot {
  background: #d2c728;
}

.errorDot {
  background: #e6376e;
}

.copyTip {
  &::v-deep .el-dialog__body {
    color: #1fb62f;
  }
}

.uploadBox {
  .uploadBoxBtn {
    text-align: center;

    .el-image {
      width: 56px;
      height: 56px;
      display: block;
      margin: 0 auto;
    }

    div {
      font-size: 14px;
      height: 24px;
    }
  }
}

.dialog-footer {
  display: flex;
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid rgb(234, 234, 234);
  .button {
    cursor: pointer;
    width: 50%;
    margin: 0;
    border: none;
    text-align: center;
    line-height: 40px;
  }
  .button:nth-child(1) {
    color: #1d1d1d;
    border-right: 1px solid rgb(234, 234, 234);
  }
  .button:nth-child(2) {
    color: #1b5bd8;
  }
}
</style>
